import { fetchMaterialList, MaterialApi } from '@/api/premium/content/material'
import { QueryMaterialRequest } from '@/api/premium/content/model/materialModel'
import { FormProps } from '@/components/Form/types'
import {
  MaterialStatus,
  MaterialType,
} from '@/components/ItemList/MaterialList/types'
import { useStore } from '@/store'
import { formatPagination } from '@/utils/antdOpFormatHelper'
import { computed, UnwrapRef, reactive, Ref } from 'vue'
import { MaterialTableState } from '../types'
import { queryMaterialFormItems } from './initData'

export default function useSearchMateries(
  materialTableState: UnwrapRef<MaterialTableState>,
  pageInfo: Ref
) {
  const store = useStore()
  const queryFormState = reactive<
    Omit<QueryMaterialRequest, 'current' | 'size'>
  >({
    id: undefined,
    sourceId: undefined,
    type: MaterialType.IMAGE,
    structure: -1,
    authorId: undefined,
    status: MaterialStatus.NORMAL,
    atlas: undefined,
    category: undefined,
    tag: undefined,
    title: undefined,
    itype: -1,
    source: -1,
  })

  const queryFormBind: FormProps = {
    model: queryFormState,
  }

  const queryFormItems = queryMaterialFormItems

  const searchMaterialList = async () => {
    const { data } = await fetchMaterialList({
      ...queryFormState,
      current: pageInfo.value.current,
      size: pageInfo.value.pageSize,
    })
    const { records, ...pageInfoData } = data
    materialTableState.tableData = records.map((record) => {
      return {
        modifyAtlasPopVisible: false,
        ...record,
      }
    })
    pageInfo.value = formatPagination(pageInfoData)
  }
  const searchMaterialLoading = computed(() =>
    store.getters['global/isOpLoading'](MaterialApi.GET_MATERIAL_LIST)
  )

  const pageChange = (page: number) => {
    pageInfo.value.current = page
    searchMaterialList()
  }

  const pageSizeChange = (current: number, pageSize: number) => {
    pageInfo.value.current = current
    pageInfo.value.pageSize = pageSize
    searchMaterialList()
  }

  const formatTotalPageText = (total: number) => `共 ${total} 个`

  return {
    queryFormState,
    queryFormBind,
    queryFormItems,
    searchMaterialLoading,
    searchMaterialList,
    pageChange,
    pageSizeChange,
    formatTotalPageText,
  }
}
